package com.jzqf.bluetooth.server

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothServerSocket
import android.bluetooth.BluetoothSocket
import android.util.Log
import com.jzqf.bluetooth.Api
import com.jzqf.bluetooth.event.EventCode
import com.jzqf.bluetooth.event.EventMessage
import org.greenrobot.eventbus.EventBus
import java.io.InputStream
import java.io.OutputStream
import java.util.*
import java.util.concurrent.Executors
import java.util.concurrent.Future

/**
 * 蓝牙服务端
 * 2020/9/18 11:39
 * @author LiuWeiHao
 */
class ServerService {
    private val TAG = "【ServerService】"

    //信息同步
    var SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")

    //文件传输
    var FILE_UUID = UUID.fromString("00001106-0000-1000-8000-00805F9B34FB")
    private val executor = Executors.newCachedThreadPool()
    private var inputStream: InputStream? = null
    private var outputStream: OutputStream? = null
    private var future: Future<*>? = null
    private var bluetoothServerSocket: BluetoothServerSocket? = null
    private var bluetoothSocket: BluetoothSocket? = null

    @Throws(Exception::class)
    fun startServer() {
        future = executor.submit {
            val bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
            if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled) {
                Log.d(TAG, "bluetoothAdapter is disEnable")
                return@submit
            }
            val bluetoothServerSocket =
                bluetoothAdapter.listenUsingRfcommWithServiceRecord(
                    "server",
                    SPP_UUID
                )
            EventBus.getDefault()
                .post(
                    EventMessage(
                        EventCode.RESULT,
                        "等待蓝牙连接 Thread=${Thread.currentThread().name}"
                    )
                )
            val bluetoothSocket = bluetoothServerSocket?.accept()
            EventBus.getDefault()
                .post(EventMessage(EventCode.RESULT, "蓝牙已连接 "))
            outputStream = bluetoothSocket?.outputStream
            inputStream = bluetoothSocket?.inputStream
            //这个去掉下次就连不上了
            while (true) {
                read()
            }
        }
    }

    private fun read() {
        inputStream?.let {
            val byteArray = ByteArray(it.available())
            if (byteArray.isNotEmpty()) {
                it.read(byteArray)
                val value = String(byteArray)
                EventBus.getDefault()
                    .post(EventMessage(EventCode.RESULT, value))
                api(value)
            }
        }

    }

    fun writeData(string: String) {
        writeData(string.toByteArray())
    }

    private fun writeData(byteArray: ByteArray) {
//        if (!checkConnect()) {
//            return
//        }
        outputStream?.write(byteArray)
        outputStream?.flush()
    }

    private fun checkConnect(): Boolean {
        if (bluetoothSocket == null) {
            EventBus.getDefault()
                .post(EventMessage(EventCode.RESULT, "蓝牙已断开连接，别TM发数据了"))
            return false
        }
        return bluetoothSocket!!.isConnected
    }

    private fun api(string: String) {
        when (string) {
            Api.searchList -> {
                writeData("${string} 返回信息:XXXXX")
            }
        }
    }

    fun close() {
        inputStream?.close()
        outputStream?.close()
        future?.cancel(true)
    }
}